package com.xjczjj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjczjj.mapper.SysUserMapper;
import com.xjczjj.model.common.Result;
import com.xjczjj.model.common.ResultCode;
import com.xjczjj.model.pojo.SysUser;
import com.xjczjj.model.qo.LoginQo;
import com.xjczjj.model.qo.UserQueryQo;
import com.xjczjj.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员表	 服务实现类
 * </p>
 *
 * @author 朱佳吉
 * @since 2024-06-05 11:39:11
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Override
    public Result login(LoginQo loginQo) {
        String password = loginQo.getPassword();
        String username = loginQo.getUsername();
        if(StringUtils.isBlank(username) && StringUtils.isBlank(password)){
            return Result.error().message("用户名不能为空");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        if(sysUser != null){
            if(sysUser.getPassword().equals(password)){
                StpUtil.login(sysUser.getId());
                String tokenValue = StpUtil.getTokenValue();
                return Result.ok(tokenValue);
            }else{
                return Result.error().message("用户名或密码错误").code(ResultCode.USERNAME_PASSWORD_ERROR);
            }
        }else{
            return Result.error().message("用户名或密码错误").code(ResultCode.USERNAME_PASSWORD_ERROR);
        }
    }

    @Override
    public IPage<SysUser> findUserListByPage(IPage<SysUser> page,UserQueryQo userQueryQo) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(userQueryQo.getStatus()!=null,SysUser::getStatus, userQueryQo.getStatus())
                .like(StringUtils.isNotEmpty(userQueryQo.getUsername()), SysUser::getUsername, userQueryQo.getUsername())
                .orderByAsc(SysUser::getId);
        return baseMapper.selectPage(page,lambdaQueryWrapper);
    }
}
